package com.gaogzhen.security.lock.reentrant;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试ReentrantLock可打断性
 */
@Slf4j(topic = "c.TestInterruptible")
public class TestInterruptible {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            try {
                // 尝试获取锁
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("获取锁失败，退出.");
                return;
            }

//            try {
//                // 尝试获取锁
//                lock.lock();
//                log.debug("获取到锁,执行后续代码...");
//            } finally {
//                lock.unlock();
//            }
        }, "t1");

        // 主线程先获取了锁
        lock.lock();

        t1.start();
        TimeUnit.SECONDS.sleep(1);
        log.debug("打断t1线程...");
        t1.interrupt();
    }
}
